import { useEffect } from 'react';

/**
 * 首屏资源优先级提升
 */
export const prioritizeFirstScreenResources = () => {
  useEffect(() => {
    // 预加载首屏关键图片
    document.querySelectorAll('img[data-critical]').forEach(img => {
      const link = document.createElement('link');
      link.rel = 'preload';
      link.as = 'image';
      link.href = img.src;
      document.head.appendChild(link);
    });

    // 延迟非关键iframe
    const lazyIframes = () => {
      document.querySelectorAll('iframe[data-lazy]').forEach(iframe => {
        iframe.src = iframe.dataset.src;
      });
    };

    // 在空闲时间或主内容加载完成后执行
    if ('requestIdleCallback' in window) {
      requestIdleCallback(lazyIframes);
    } else {
      window.addEventListener('load', lazyIframes);
    }
  }, []);
};

/**
 * 骨架屏自动移除
 */
export const useSkeletonCleanup = (dependencies = []) => {
  useEffect(() => {
    const skeletonElements = document.querySelectorAll('[data-skeleton]');
    if (skeletonElements.length > 0) {
      const fadeOut = () => {
        skeletonElements.forEach(el => {
          el.style.transition = 'opacity 0.3s';
          el.style.opacity = '0';
          setTimeout(() => el.remove(), 300);
        });
      };

      // 确保内容已经完全渲染
      setTimeout(fadeOut, 100);
    }
  }, dependencies);
};

/**
 * 主内容加载状态检测
 */
export const useMainContentLoaded = () => {
  const [isLoaded, setIsLoaded] = useState(false);

  useEffect(() => {
    const mainContent = document.querySelector('main');
    if (!mainContent) {
      setIsLoaded(true);
      return;
    }

    const observer = new MutationObserver(() => {
      if (mainContent.textContent.trim().length > 50) {
        setIsLoaded(true);
        observer.disconnect();
      }
    });

    observer.observe(mainContent, {
      childList: true,
      subtree: true,
      characterData: true
    });

    // 超时强制标记为已加载
    const timeout = setTimeout(() => {
      setIsLoaded(true);
      observer.disconnect();
    }, 5000);

    return () => {
      observer.disconnect();
      clearTimeout(timeout);
    };
  }, []);

  return isLoaded;
};
